package com.campusrecruitment.common;

import com.alibaba.fastjson.JSON;
import org.springframework.core.io.Resource;


import java.io.*;

public class JsonUtils {
         //文件路径
         public File systemSetting;

         public JsonUtils(File systemSetting){
             this.systemSetting=systemSetting;
         }
      public String readString() {
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(systemSetting), "UTF-8"));
            StringBuilder content = new StringBuilder();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                content.append(line);
            }
            return content.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 写入文件
     * @param
     */
    public void writeString(String content) {
        BufferedWriter bufferedWriter = null;
        try {
            bufferedWriter = new BufferedWriter(new FileWriter(systemSetting));
            bufferedWriter.write(content);
            bufferedWriter.flush();
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭流释放资源
                bufferedWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 读取json类型的文件
     * @param
     * @param c
     * @param <T> 转化的对象类型
     * @return
     */
    public <T> T readJson(Class<T> c) {
        String content = readString();
        return JSON.parseObject(content,c);
    }

    /**
     * 写入json类型的文件
     * @param
     * @param o
     */
    public void writeJson(Object o) {
        String jsonString = JSON.toJSONString(o);
        writeString(jsonString);
    }

}
